'use strict';

define(function(require,exports,module){
	
	var React = require('react');
	var $ = require('jquery');
	var moment = require('moment');

	var publicObj = require('lib/public');
	var token = publicObj.get_token();
	
	/*下拉框*/
	var SelectOption = require('components/partial/SelectOption');
	
	/*DATE下拉框*/
	var SelectOptionDate = require('components/partial/SelectOptionDate');
	
	//折线图
	var DayOpenLineDiagram = require('components/diagram/DayOpenLineDiagram');

    var UserRecordAreaBasic = require('components/diagram/AreaDiagram/UserRecordAreaBasic');

    //TimeBucket
    var UserRecordTimeBucket = require('./UserRecordDiagram/TimeBucket');
	
    /*Loading状态*/
    var ReactLoading = require('../partial/ReactLoading');
	
	module.exports = React.createClass({displayName: "exports",
		handleDateChange:function(event){
			var date = event.target.value;
			this.setState({'date':date});
            this.setState({'hardware':''});
			this.loadData(date,'');
		},
		handleHardwareChange:function(event){
			var hardware = event.target.value;
			this.setState({'hardware':hardware});
			this.loadData(this.state.date,hardware);
		},
		loadData:function(date,hardware){
			
			this.setState({data:[]});
			if(date){
				var year = date.substring(0,4);
				var month = date.substring(4,6);
				var day = date.substring(6,8);
				var start_date = Math.round(new XDate(new XDate(year+"-"+month+"-"+day+" 00:00:00").toString('yyyy-MM-dd')+' 00:00:00').getTime()/1000);
				var end_date = Math.round(new XDate(new XDate(year+"-"+month+"-"+day+" 00:00:00").addDays(1).toString('yyyy-MM-dd')+' 00:00:00').getTime()/1000);

                var sql;
                if(hardware == 'iphone'){
                    sql = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),'%H') as time,count(*) as value\
						  FROM qeeniao.app_info\
						 where platform = 'iOS'\
						   and(create_time>= '"+start_date+"'\
						   and create_time< '"+end_date+"')\
						 group by time\
						 order by time ASC";
                }else if(hardware == 'android'){
                    sql = "SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(create_time),'%H') as time,count(*) as value\
						  FROM qeeniao.app_info\
						 where platform = 'Android'\
						   and(create_time>= '"+start_date+"'\
						   and create_time< '"+end_date+"')\
						 group by time\
						 order by time ASC";
                }else{
					sql = "SELECT count(*) as value,\
							FROM_UNIXTIME(left(ctime,10), '%H') as time\
							FROM qeeniao.record\
							where left(ctime,10) >= "+start_date+" \
								and left(ctime,10) < "+end_date+"\
							group by time\
							order by time ASC";
				}

				$.ajax({
					url:this.props.url,
					data:{sql:sql,'access_token':token},
					type:'post',
					dataType:'json',
					success:function(o){
						var tmp = [];
						tmp.push(o);
						if(o){
							if(this.isMounted()) {
								this.setState({'data': tmp});
							}
						}
					}.bind(this),
					error:function(xhr,status,err){
						console.error(sql,status,err.toString());
					}.bind(this)
				});
			}
		},
        loadDefaultData:function(){
            var token = publicObj.get_token();

            var tmp = [];
            var url = this.props.url;

            var timestamp = Math.round(new XDate(new XDate().addDays(-10).toString("yyyy-MM-dd")+" 00:00:00").getTime() / 1000);
            
            var sql_arr = [];

			var all_sql = "SELECT count(*) as value,\
							FROM_UNIXTIME(left(ctime,10), '%Y-%m-%d') as name\
							FROM qeeniao.record\
							where left(ctime,10) > "+timestamp+"\
							group by name\
							order by name ASC";

			sql_arr.push({'name':'all','sql':all_sql});

            sql_arr.forEach(function(v,k){
                $.ajax({
                    url:url,
                    data:{sql:v.sql,'access_token':token},
                    type:'post',
                    dataType:'json',
                    success:function(o){
                        tmp = this.state.all_data;
                        tmp[v.name] = o;
						if(this.isMounted()) {
							this.setState({'all_data': tmp});
						}
                    }.bind(this),
                    error:function(xhr,status,err){
                        console.error(v.sql,status,err.toString());
                    }
                });
                this.setState({'all_data':tmp});
            }.bind(this));
        },
		getInitialState:function(){
			var timestamp = Math.round(new XDate(new XDate().addDays(-10).toString("yyyy-MM-dd")+" 00:00:00").getTime() / 1000);
            
			var sql = "SELECT count(*) as value,\
							FROM_UNIXTIME(left(ctime,10), '%Y-%m-%d') as name\
							FROM qeeniao.record\
							where left(ctime,10) > "+timestamp+"\
							group by name\
							order by name ASC";

			return {
				'data':[],
                'all_data':{'ios':[],'android':[],'all':[]},
				'date':'',
				'ajax_data':{'sql':sql,'access_token':token}
			}
		},
		render:function(){
            var diagram;

            if(this.state.data.length > 0){
                diagram = this.state.data.map(function(item){
                    return (
                        React.createElement(DayOpenLineDiagram, {className: "", id: "UserRecord", id_name: "UserRecord", title: "用户单日记账次数", yName: "记账次数", yUnit: "（时/次数）", url: "", data: item})
                    );
                });
            }else{
				diagram = React.createElement(UserRecordAreaBasic, {className: "", id: "UserRecordMuliti", id_name: "UserRecordMuliti", y: "记账次数", title: "每日记账次数", ajax_data: this.state.ajax_data, url: this.props.url, interval: "300000"});
            }

			return (
				React.createElement("div", {className: "col-xs-6"}, 
					React.createElement("div", {className: "row bgwhite"}, 
						React.createElement("div", {className: "col-xs-4 bs-callout bs-callout-info"}, 
							React.createElement("h4", null, this.props.title, ": ")
						), 
						React.createElement("div", {className: "col-xs-4 "}, 
							React.createElement(SelectOptionDate, {handleDateChange: this.handleDateChange, data: this.props.data})
						), 
						React.createElement("div", {className: "col-xs-2", style: {margin:'4px 0'}}, 
							React.createElement("button", {onClick: this.createHandle, className: "btn btn-primary btn", "data-toggle": "modal", "data-target": "#UserRecordTimeBucket"}, "更多")
						), 
                        React.createElement(UserRecordTimeBucket, {id: "UserRecordTimeBucket", url: this.props.url})
					), 
					React.createElement("div", {className: "row"}, 
					diagram
					)
				)
			);
		}
	});

});